// pages/goods/detail/detail.js
const util = require('../../../utils/util.js')
var WxParse = require('../../../wxParse/wxParse.js');

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab: 0,
    tabClass: ['text-select', 'text-normal', 'text-normal'],
    goodsId: 0, //商品ID
    images: [],
    goodsInfo: [],
    domain: app.globalData.domain,
    swiperHeight: 0,
    goodsNum: 1, //商品数量
    page: 1, //默认加载第一页评价
    textStates: ["view-btns-text-normal", "view-btns-text-select"],
    price: 0,
    collectState: 0,
    spec_key:'',
    spec_key_value:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 第三季升级，分享给朋友推广注册，涉及分销系统
    // 商品ID
    var goods_id = options.objectId
    // 上线ID
    var parent_id = options.uid
    // 存在则是推广而来
    if (goods_id != undefined && parent_id != undefined){
      // 调用推广接口
      this.userShare(parent_id)
    }

    this.setData({ goodsId: options.goodsId, swiperHeight: util.getWindowSize().screenWidth })
    this.getGoodsInfo(1)
  },

  userShare: function (parent_id) {
    // 获取code，提交接口进行注册
    wx.login({
      success: res => {
        if (res.code){
          var url = 'User/userShare'
          var params = {
            js_code: res.code,
            parent_id: parent_id
          }
          util.wxRequest(url, params, data => {
          }, data => { }, data => { })
        }
      }
    })
  },

  getGoodsInfo:function(page) {
    var url = 'Goods/goodsInfo'
    var params = { 
      id: this.data.goodsId,
      page: page,
      openid: app.globalData.openid,
      token: app.globalData.userInfo == null ? '' : app.globalData.userInfo.token
    }
    util.wxRequest(url, params, data => {
      if (data.code == 200) {
        WxParse.wxParse('article', 'html', data.info.content, this, 5)

        // 第三季升级
        var goodsInfo = data.info
        if(page > 1){
          // 原评价
          var comment = this.data.goodsInfo.comment
          // 新评价(后取出的一页数据)
          var newComment = data.info.comment
          // 将新评价遍历push到原评价中
          if (newComment.length == 0){
            wx.showToast({
              title: '没有更多评价了',
              icon: 'none'
            })
          }else{
            for (var i in newComment){
              comment.push(newComment[i])
            }
          }
          goodsInfo.comment = comment
        }
        wx.stopPullDownRefresh()

        this.setData({ images: data.images, goodsInfo: goodsInfo, collectState: goodsInfo.collectState })
        if (goodsInfo.spec_type == 2){
          this.getPrice()
        }else{
          this.setData({ price: goodsInfo.price })
        }
      }
    }, data => { }, data => { })
  },

  propClick: function(e) {
    var pos = e.currentTarget.dataset.pos
    var index = e.currentTarget.dataset.index
    var goodsInfo = this.data.goodsInfo
    for (var i = 0; i < goodsInfo.goods_spec[pos].length; i++){
      if(i == index){
        goodsInfo.goods_spec[pos][i].isClick = 1
      }else{
        goodsInfo.goods_spec[pos][i].isClick = 0
      }
    }
    this.setData({ goodsInfo: goodsInfo })
    this.getPrice()
  },

  getPrice: function() {
    var goodsInfo = this.data.goodsInfo
    if (goodsInfo.spec_type == 2){
      var spec = ""
      for (var i = 0; i < goodsInfo.goods_spec.length; i++) {
        for (var j = 0; j < goodsInfo.goods_spec[i].length; j++) {
          if (goodsInfo.goods_spec[i][j].isClick == 1) {
            if (spec == '') {
              spec = goodsInfo.goods_spec[i][j].item_id
            } else {
              spec = spec + "_" + goodsInfo.goods_spec[i][j].item_id
            }
          }
        }
      }
      // 第三季修正（会员ariclee提出）
      if (goodsInfo['goods_spec_price'][spec] === undefined){
        var spec_array = spec.split('_').sort()
        spec = spec_array.join('_')
      }

      var price = goodsInfo['goods_spec_price'][spec].price
      this.setData({ spec_key: spec, spec_key_value: goodsInfo['goods_spec_price'][spec].key_value})
    }else{
      var price = goodsInfo.price
    }
    
    price = price * this.data.goodsNum
    this.setData({ price: price.toFixed(2) })
  },

  /**
   * 购买数量减
   */
  bindMinus: function() {
    var num = this.data.goodsNum
    if(num >1 ){
      num--
      //第三季升级
      this.setData({ goodsNum: num })
      this.getPrice()
    }
  },

  /**
   * 购买数量值
   */
  inputing: function(e){
    var num = e.detail.value
    if(num<1){
      num = 1
    }
    this.setData({ goodsNum: num })
    this.getPrice()
  },

  /**
   * 购买数量加
   */
  bindPlus: function () {
    var num = this.data.goodsNum
    num++
    this.setData({ goodsNum: num })
    this.getPrice()
  },

  /**
   * 商品收藏或取消收藏
   */
  addCollect: function (e){
    // 第三季修正
    if (util.getLoginStatus() == true){
      var gid = e.currentTarget.dataset.id
      var url = 'Goods/collectGoods'
      var params = {
        gid: gid,
        openid: app.globalData.openid,
        token: app.globalData.userInfo.token
      }
      util.wxRequest(url, params, data => {
        if (data.code == 200) {
          this.setData({ collectState: data.state })
          wx.showToast({
            title: data.msg,
            icon: 'success',
            duration: 2000
          })
        }
      }, data => { }, data => { })
    }
  },

  /**
   * 加入购物车
   */
  addCart: function(){
    // 第三季修正
    if (util.getLoginStatus() == true){
      var gid = this.data.goodsId
      var url = 'Cart/addCart'
      var params = {
        gid: gid,
        goodsNum: this.data.goodsNum,
        openid: app.globalData.openid,
        token: app.globalData.userInfo.token,
        spec_key: this.data.spec_key,
        spec_key_value: this.data.spec_key_value
      }
      util.wxRequest(url, params, data => {
        if (data.code == 200) {
          app.globalData.login = true
          wx.showToast({
            title: data.msg,
            icon: 'success',
            duration: 2000
          })
        } else {
          app.globalData.login = false
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }, data => { }, data => { })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作--下拉刷新
   */
  onPullDownRefresh: function () {
    // 第三季升级
    // 只有下拉评价标签时才刷新
    if(this.data.tab == 2){
      wx.showToast({
        title: '刷新中',
        icon: 'loading'
      })
      this.setData({ goodsInfo: [], page: 1 })
      this.getGoodsInfo(1)
    }else{
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 页面上拉触底事件的处理函数--上拉加载
   */
  onReachBottom: function () {
    // 第三季升级
    // 只有上拉评价标签时才加载
    if (this.data.tab == 2){
      wx.showToast({
        title: '加载中',
        icon: 'loading'
      })
      this.getGoodsInfo(++this.data.page)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 第三季更新，用于分销推广
    var goods_name = this.data.goodsInfo.name
    //地址中传入商品ID和用户ID
    var objectId = this.data.goodsInfo.id
    if (app.globalData.login){
      var user_id = app.globalData.userInfo.id
    }
    return {
      title: goods_name,
      path: '/pages/goods/detail/detail?objectId=' + objectId + '&uid=' + user_id + '&goodsId=' + objectId
    }
  },

  tabClick: function(e) {
    var index = e.currentTarget.dataset.index
    var classs = ['text-normal', 'text-normal', 'text-normal']
    classs[index] = 'text-select'
    this.setData({ tabClass: classs, tab:index})
  },

  /**
   * 立即购买：检查该商品是否已加入购物车，
   * 加入则跳转购物车页面，未加入则先加入购物车再跳转
   */
  buy: function() {
    // 第三季修正
    if (util.getLoginStatus() == true){
      var url = 'Cart/checkCart'
      var params = {
        goodsNum: this.data.goodsNum,
        gid: this.data.goodsInfo.id,
        openid: app.globalData.openid,
        token: app.globalData.userInfo.token,
        spec_key: this.data.spec_key,
        spec_key_value: this.data.spec_key_value
      }
      util.wxRequest(url, params, data => {
        if (data.code == 200) {
          wx.switchTab({
            url: '../../cart/cart',
          })
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }, data => { }, data => { })
    }
  },

  showShareModal: function() {
    this.setData({ share_modal_active: "active"})
  },

  shareModalClose: function () {
    this.setData({ share_modal_active: "" })
  },

  redirectToHome: function () {
    wx.switchTab({
      url: '../../index/index',
    })
  }

})